/* ============================================================================= */
/*               TABLE 4 - SECURED LOAN PROPENSITY & COLLATERAL CHANNEL          */
/* ============================================================================= */

clear all

/* ============================================================================= */
/*              PREPARING MATCHED SAMPLE WEIGHT FILES                            */
/* ============================================================================= */

* Save unique siren-weight pairs for rejected loans
use "$output\matched_sample_rejected_table6.dta", clear
keep siren weight
sort siren weight
bys siren weight: gen nb = _n
keep if nb == 1
drop nb
save "$output\matched_sample_rejected_table6_weight.dta", replace

* Save unique siren-weight pairs for P2P loans
use "$output\matched_sample_p2p_table6.dta", clear
keep siren weight
sort siren weight
bys siren weight: gen nb = _n
keep if nb == 1
save "$output\matched_sample_p2p_table6_weight.dta", replace

* Save unique siren-weight pairs for P2P loans (Investment loans only)
use "$output\matched_sample_p2p_table6_FI.dta", clear
keep siren weight
sort siren weight
bys siren weight: gen nb = _n
keep if nb == 1
save "$output\matched_sample_p2p_table6_FI_weight.dta", replace

* Save unique siren-weight pairs for P2P loans (Non-investment loans)
use "$output\matched_sample_p2p_table6_noFI.dta", clear
keep siren weight
sort siren weight
bys siren weight: gen nb = _n
keep if nb == 1
save "$output\matched_sample_p2p_table6_noFI_weight.dta", replace

/* ============================================================================= */
/*                 IMPORT DATA & PREPARE COLLATERAL CHANNEL TEST PANEL           */
/* ============================================================================= */

import delimited "$input\collateral_channel_test_panel_purpose.csv", clear
gen time = date(date, "YMD")
gen qdate = qofd(time)
format time %td
format qdate %tq

/* ------------------------------------------------------------------------------
   Step 2: Industry Classification Adjustments
------------------------------------------------------------------------------ */

replace industry = "public" if inlist(industry, "P", "Q", "R", "S")
replace industry = "DE" if inlist(industry, "D", "E")
replace industry = "FL" if inlist(industry, "F", "L")

* Remove agriculture, public administration, and finance/insurance
drop if inlist(industry, "A", "K", "O")

* Remove industries with insufficient firms
drop if inlist(industry, "B", "DE", "0000Z")

egen industry10 = group(industry)

tsset siren qdate, quarterly

* Keep only observations within the required time window
keep if qdate < qofd(date("20200101", "YMD"))
keep if qdate > qofd(date("20160930", "YMD"))

* Start log file
capture log close
log using "$logs\table_6_secured_loan_propensity_purpose.log", replace

/* ------------------------------------------------------------------------------
   Step 3: Generate Loan & Collateral Variables
------------------------------------------------------------------------------ */

replace outsideloan = 0 if outsideloan == .
gen ifp = ifploan > 0
gen collateralized = (collateral > 0 & loan > 0)
gen outside = outsideloan > 0

/* ------------------------------------------------------------------------------
   Step 4: Identify First Loan Date per Firm
------------------------------------------------------------------------------ */

preserve
    keep siren ifploan qdate outsideloan
    keep if ifploan > 0 | outsideloan > 0
    rename qdate qdateloan
    keep siren qdateloan
    sort siren qdateloan
    quietly by siren: gen dup = cond(_N == 1, 0, _n)
    drop if dup > 1
    keep siren qdateloan
    save "$output\collateral_channel_mdateloan_p2p.dta", replace
restore

/* ============================================================================= */
/*       MATCHED SAMPLE - REJECTED  											 */
/* ============================================================================= */

preserve
    merge m:1 siren using "$output\collateral_channel_mdateloan_rejected.dta"
    keep if _merge == 1 | _merge == 3
    drop _merge

    gen post = (qdateloan < qdate)
    egen nesc = group(industry)
    rename pclopen opening
    rename pclliquidate dead

    merge m:1 siren using "$output\matched_sample_rejected_table6_weight.dta"
    keep if _merge == 3
    drop _merge

    drop p2p
    gen p2p = accepted

    * Full sample with propensity score weights
    eststo reg4: reghdfe collateralized i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.qdate) cluster(siren) 
    estadd local firm "Y", replace 
    estadd local indyear "Y", replace  
    estadd local psmed "Y", replace 

    * Investment loans only
    eststo reg4invest: reghdfe collateralized i1.p2p##i1.post [pweight=weight] if (ifpforinvest == 1 | p2p == 0), ///
        a(i.siren i.nesc#i.qdate) cluster(siren) 
    estadd local firm "Y", replace 
    estadd local indyear "Y", replace  
    estadd local psmed "Y", replace  

    * Non-investment loans only
    eststo reg4notinvest: reghdfe collateralized i1.p2p##i1.post [pweight=weight] if (ifpforinvest == 0 | p2p == 0), ///
        a(i.siren i.nesc#i.qdate) cluster(siren) 
    estadd local firm "Y", replace 
    estadd local indyear "Y", replace  
    estadd local psmed "Y", replace  

restore

	
//----------------------------------------------------------------------------//
			 * Table DiD P2P
//----------------------------------------------------------------------------//

merge m:1 siren using "$output\collateral_channel_mdateloan_p2p.dta"
keep if _merge == 1 | _merge == 3
drop _merge

gen post = (qdateloan < qdate)  // Define post-treatment period

egen nesc = group(industry)  // Group industry for fixed effects
rename pclopen opening
rename pclliquidate dead

/* ============================================================================= */
/*               MATCHED SAMPLE REGRESSIONS                                     */
/* ============================================================================= */

preserve
    merge m:1 siren using "$output\matched_sample_p2p_table6_weight.dta"
    keep if _merge == 3
    drop _merge

    eststo reg2: reghdfe collateralized i1.p2p##i1.post [pweight=weight], ///
        a(i.siren i.nesc#i.qdate) cluster(siren) 
    estadd local firm "Y", replace 
    estadd local indyear "Y", replace  
    estadd local psmed "Y", replace 
restore

preserve
    merge m:1 siren using "$output\matched_sample_p2p_table6_FI_weight.dta"
    keep if _merge == 3
    drop _merge

    eststo reg2invest: reghdfe collateralized i1.p2p##i1.post [pweight=weight], ///
        a(i.siren i.nesc#i.qdate) cluster(siren) 
    estadd local firm "Y", replace 
    estadd local indyear "Y", replace  
    estadd local psmed "Y", replace 
restore

preserve
    merge m:1 siren using "$output\matched_sample_p2p_table6_noFI_weight.dta"
    keep if _merge == 3
    drop _merge

    eststo reg2notinvest: reghdfe collateralized i1.p2p##i1.post [pweight=weight], ///
        a(i.siren i.nesc#i.qdate) cluster(siren) 
    estadd local firm "Y", replace 
    estadd local indyear "Y", replace  
    estadd local psmed "Y", replace  
restore

/* ============================================================================= */
/*               EXPORT REGRESSION RESULTS TO LaTeX                              */
/* ============================================================================= */

* Export matched sample results
* Table 6a
esttab reg2 reg2invest reg2notinvest using "$tables\Table_6_fin_bank_matched.tex", replace ///
    noomitted nobase fragment gap booktabs label nonote noobs nolines ///
    b(%9.3f) drop(_cons) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) posthead(\midrule) ///
    mtitles("1(Secured)" "1(Secured)" "1(Secured)") ///
    order(1.p2p#1.post 1.post) varlabel(1.post "Post" 1.p2p#1.post `"FinTech $\times$ Post"') ///
    stats(firm indyear N r2, label(`"Firm FE"' `"Industry-Quarter FE"' `"\midrule N"' `"R-sq"') ///
    layout("\multicolumn{1}{c}{@}") fmt(%9.0fc %9.0fc %9.0fc %9.2f))

* Export matched sample results for rejected loans
* Table 6b
esttab reg4 reg4invest reg4notinvest using "$tables\Table_6_acc_rej_matched.tex", replace ///
    noomitted nobase fragment gap booktabs label nonote noobs nolines ///
    b(%9.3f) drop(_cons) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) posthead(\midrule) ///
    mtitles("1(Secured)" "1(Secured)" "1(Secured)") ///
    order(1.p2p#1.post 1.post) varlabel(1.post "Post" 1.p2p#1.post `"FinTech $\times$ Post"') ///
    stats(firm indyear N r2, label(`"Firm FE"' `"Industry-Quarter FE"' `"\midrule N"' `"R-sq"') ///
    layout("\multicolumn{1}{c}{@}") fmt(%9.0fc %9.0fc %9.0fc %9.2f))

log close
